<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="username" autocomplete="off">
  <button id="addRoom">加入聊天室</button><br/><br/>
  <input type="text" id="msg" autocomplete="off">
  <button id="sendMsg">发送</button><span id="write"></span>
  <div id="content"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script>
  $(function() {
    var socket = io()
    // socket.on()  // 监听事件
    
    // 加入聊天室
    $('#addRoom').click(function() {
      if ($('#username').val() === '') {
        return false
      }
      socket.emit('username', $('#username').val())
      $('#username').val('')
    })
    socket.on('username', function(user) {
      $('#content').append($('<p>').text(user + '进来了'))
    })
    // 退出聊天室(在客户端断开连接是触发)
    socket.on('remove', function(user) {
      $('#content').append($('<p>').text(user + '离开了'))
    })
    // 添加正在输入...
    $('#msg').keyup(function() {
      socket.emit('writing')
    })
    socket.on('writing', function(user) {
      if ($('#write').text() === '') {
        $('#write').append($('<p>').text(user + '正在输入....'))
      }
    })
    // 发送消息
    $('#sendMsg').click(function() {
      socket.emit('msg', $('#msg').val())
      $('#msg').val('')
      return false
    })
    socket.on('msg', function(msg, user) {
      $('#write').text('')
      $('#content').append($('<p>').text(user + '发送消息:' + msg))
    })
  })
  </script>
</body>
</html>